package com.kaka.web_maven.controller;

import com.kaka.web_maven.dao.UserDao;
import com.kaka.web_maven.entity.Users;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.text.SimpleDateFormat;

@WebServlet(name = "UserAddServlet",urlPatterns = "/UserAddServlet")
public class UserAddServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取数据

        try{
            String username = request.getParameter("username");
            System.out.println(username);
            int age = Integer.parseInt(request.getParameter("age"));
            Date birth =  new SimpleDateFormat("yyyy-MM-dd").parse(request.getParameter("birth"));
            //将数据封装成user对象
            Users user = new Users();
            user.setUsername(username);
            user.setAge(age);
            user.setBirth(birth);
           //调用UserDao保存方法保存数据
            UserDao dao = new UserDao();
            dao.save(user);

            //页面转换
            request.getRequestDispatcher("/UsersServlet").forward(request,response);
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
